<?php

namespace app\demo\service;

use app\demo\enum\Sex;
use app\demo\enum\Hobby;
use app\demo\enum\Grade;
use app\demo\enum\State;
use yunj\enum\TableEvent;
use app\demo\model\Example as Model;

class Example {

    private $model;

    private static $instance;

    private function __construct() {
        $this->model = new Model();
    }

    public static function instance() {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    // list general example
    public function filterByListGeneralExample($state) {
        $filter = [
            'name_cn' => ['title' => '中文姓名', 'verify' => 'chs'],
            'name_en' => ['title' => '英文姓名', 'verify' => 'chsDash'],
            'grade' => [
                'title' => '年级',
                'type' => 'select',
                'verify' => 'in:0,1,2,3,4',
                'options' => [0 => '请选择', 1 => '一年级', 2 => '二年级', 3 => '三年级', 4 => '四年级']
            ],
        ];
        return $filter;
    }

    public function toolbarByListGeneralExample($state) {
        $toolbar = ['add' => ['type' => 'open_popup', 'title' => '添加', 'icon' => 'layui-icon layui-icon-add-circle', 'url' => url('add')]];
        switch ($state) {
            case State::NORMAL:
                $toolbar += [
                    State::RECYLE_BIN => ['type' => 'async_event', 'title' => '移入回收站', 'dropdown' => true],
                ];
                break;
            case State::RECYLE_BIN:
                $toolbar += [
                    State::NORMAL => ['type' => 'async_event', 'title' => '还原', 'dropdown' => true],
                    State::DELETED => ['type' => 'async_event', 'title' => '永久删除', 'dropdown' => true],
                ];
                break;
        }
        return $toolbar;
    }

    public function defaultToolbarByListGeneralExample($state) {
        return ['filter', 'export', 'print'];
    }

    public function colsByListGeneralExample($state) {
        $cols = [
            'id' => ['type' => 'checkbox'],
            'avatar' => ['title' => '头像', 'align' => 'center', 'templet' => 'img', 'default' => '/static/yunj/img/default.png'],
            'name_cn' => ['title' => '中文姓名'],
            'name_en' => ['title' => '英文姓名', 'hide' => 'yes'],
            'album' => ['title' => '相册', 'templet' => 'imgs', 'default' => '/static/yunj/img/default.png'],
            'age' => ['title' => '年龄', 'align' => 'center', 'sort' => true, 'hide' => 'mobile_hide'],
            'area' => ['title' => '地区', 'align' => 'center', 'templet' => 'area', 'hide' => 'mobile_hide'],
            'document' => ['title' => '个人文档', 'templet' => 'file', 'hide' => 'mobile_hide'],
            'other_document' => ['title' => '其他文档', 'templet' => 'files', 'hide' => 'yes'],
            'grade' => ['title' => '年级', 'align' => 'center', 'templet' => '{{#  if(d.grade === 1){ }}一年级{{#  }else if(d.grade === 2){ }}二年级{{#  }else{ }}其他{{#  } }}'],
            'category_ids' => ['title' => '喜欢的分类', 'templet' => 'enum', 'options' => Category::instance()->options(), 'hide' => 'mobile_hide'],
            'color' => ['title' => '喜欢的颜色', 'templet' => 'color', 'hide' => 'mobile_hide'],
            'create_time' => ['title' => '添加时间', 'align' => 'center', 'hide' => 'mobile_hide_hide', 'templet' => 'datetime'],
            'update_time' => ['title' => '更新时间', 'align' => 'center', 'hide' => 'yes', 'templet' => 'datetime'],
            'demo_show_time' => [
                'title' => '操作时间',
                'hide' => 'yes',
                'templet' => 'show_time',
            ],
            'action' => [
                'title' => '操作',
                'templet' => 'action',    // 避免和系统action函数名冲突
                'options' => [
                    'edit' => ['type' => 'open_popup', 'title' => '详情', 'icon' => 'layui-icon layui-icon-survey', 'url' => url('edit')]
                ]
            ]
        ];
        switch ($state) {
            case State::NORMAL:
                $cols['action']['options'] += [
                    State::RECYLE_BIN => ['type' => 'async_event', 'title' => '移入回收站', 'dropdown' => true],
                ];
                break;
            case State::RECYLE_BIN:
                $cols['action']['options'] += [
                    State::NORMAL => ['type' => 'async_event', 'title' => '还原', 'dropdown' => true],
                    State::DELETED => ['type' => 'async_event', 'title' => '永久删除', 'dropdown' => true]
                ];
                break;
        }
        return $cols;
    }

    public function countByListGeneralExample($filter) {
        // 固定参数
        $state = $filter['state'];
        $ids = $filter['ids'];
        // 筛选表单参数
        $name_cn = $filter['name_cn'];
        $name_en = $filter['name_en'];
        $grade = $filter['grade'];
        $whereArr = [];
        $whereArr[] = $state ? ['state', 'eq', $state] : ['state', 'neq', State::DELETED];
        if ($ids) $whereArr[] = ['id', 'in', $ids];
        if ($name_cn) $whereArr[] = ['name_cn', 'like', '%' . $name_cn . '%'];
        if ($name_en) $whereArr[] = ['name_en', 'like', '%' . $name_en . '%'];
        if ($grade) $whereArr[] = ['grade', 'eq', $grade];
        return $this->model->getOwnCount($whereArr);
    }

    public function itemsByListGeneralExample($limit_start, $limit_length, $filter, $sort) {
        // 固定参数
        $state = $filter['state'];
        $ids = $filter['ids'];
        // 筛选表单参数
        $name_cn = $filter['name_cn'];
        $name_en = $filter['name_en'];
        $grade = $filter['grade'];
        $whereArr = [];
        $whereArr[] = $state ? ['state', 'eq', $state] : ['state', 'neq', State::REMOVED];
        if ($ids) $whereArr[] = ['id', 'in', $ids];
        if ($name_cn) $whereArr[] = ['name_cn', 'like', '%' . $name_cn . '%'];
        if ($name_en) $whereArr[] = ['name_en', 'like', '%' . $name_en . '%'];
        if ($grade) $whereArr[] = ['grade', 'eq', $grade];
        $orderArr = $sort + ['id' => 'desc'];
        $items = $this->model->getOwnRows($whereArr, ["*"], $orderArr, $limit_start, $limit_length);
        foreach ($items as &$v) {
            $v['area'] = ['province' => $v['province'], 'city' => $v['city'], 'district' => $v['district']];
            $v['demo_show_time'] = $v['create_time'];
        }
        return $items;
    }

    public function eventByListGeneralExample($event, $ids) {
        foreach ($ids as $id) {
            $whereArr = [['id', 'eq', $id]];
            switch ($event) {
                case State::NORMAL:
                    $updateData = ['state' => State::NORMAL];
                    $whereArr[] = ['state', 'eq', State::RECYLE_BIN];
                    break;
                case State::RECYLE_BIN:
                    $updateData = ['state' => State::RECYLE_BIN];
                    $whereArr[] = ['state', 'eq', State::NORMAL];
                    break;
                case State::DELETED:
                    $updateData = ['state' => State::DELETED];
                    $whereArr[] = ['state', 'eq', State::RECYLE_BIN];
                    break;
                default:
                    return error_json();
            }
            if ($updateData) $this->model->change($updateData, $whereArr);
        }
        return success_json();
    }

    public function importByListGeneralExample($state) {
        return url("demo/importDemo/index");
    }

    // list sort example

    public function defaultToolbarByListSortExample($state) {
        return ['filter', 'export', 'print'];
    }

    public function colsByListSortExample($state) {
        $cols = [
            'sort' => ['title' => '序号', 'align' => 'center'],
            'id' => ['title' => 'ID', 'align' => 'center'],
            'name_cn' => ['title' => '中文姓名'],
            'name_en' => ['title' => '英文姓名'],
            'age' => ['title' => '年龄', 'align' => 'center', 'hide' => 'mobile_hide_hide'],
            'grade' => [
                'title' => '年级',
                'align' => 'center',
                'templet' => 'enum',
                'options' => Grade::options(),
            ],
            'drag_sort_action' => ['templet' => 'drag_sort'],
        ];
        return $cols;
    }

    public function countByListSortExample($filter) {
        // 固定参数
        $ids = $filter['ids'];

        $whereArr = [];
        if ($ids) $whereArr[] = ['id', 'in', $ids];
        $whereArr[] = ['state', 'neq', State::DELETED];
        $whereArr[] = ['sort', 'elt', 20];
        return $this->model->getOwnCount($whereArr);
    }

    public function itemsByListSortExample($limit_start, $limit_length, $filter, $sort) {
        // 固定参数
        $ids = $filter['ids'];

        $whereArr = [];
        if ($ids) $whereArr[] = ['id', 'in', $ids];
        $whereArr[] = ['state', 'neq', State::DELETED];
        $items = $this->model->getOwnRows($whereArr, ["*"], ['sort' => 'asc'], 0, 20);
        foreach ($items as &$item) {
            $item['enum_test'] = "[1,2,3]";
            $item['enum_test'] = 1;
        }
        return $items;
    }

    public function eventByListSortExample($event, $ids) {
        $i = 0;
        foreach ($ids as $id) {
            $whereArr = [['id', 'eq', $id]];
            switch ($event) {
                case TableEvent::SORT:
                    $updateData = ['sort' => $i + 1];
                    $whereArr[] = ['state', 'neq', State::DELETED];
                    break;
                default:
                    return error_json();
            }
            if ($updateData) $this->model->change($updateData, $whereArr);
            $i++;
        }
        return success_json();
    }

    // add general example

    public function fieldByAddGeneralExample($tab) {
        $field = [];
        switch ($tab) {
            case 'base':
                $field = [
                    'avatar' => [
                        'title' => '头像',
                        'type' => 'img',
                    ],
                    'name_cn' => ['title' => '中文姓名', 'verify' => 'require|chs', 'desc' => '只能输入汉字'],
                    'name_en' => ['title' => '英文姓名', 'verify' => 'require|chsDash', 'desc' => '只能输入汉字、字母、数字和下划线_及破折号-'],
                    'sex' => [
                        'title' => '性别',
                        'type' => 'radio',
                        'verify' => 'require|in:man,woman',
                        'options' => Sex::options()
                    ],
                    'album' => [
                        'title' => '相册',
                        'type' => 'imgs',
                        'max' => 3,
                    ],
                    'color' => [
                        'title' => '喜欢的颜色',
                        'type' => 'color',
                    ],
                    'age' => ['title' => '年龄', 'verify' => 'require|positiveInteger'],
                    'grade' => [
                        'title' => '年级',
                        'type' => 'select',
                        'search' => true,
                        'verify' => 'require|in:1,2,3,4',
                        'options' => Grade::options()
                    ],
                    'hobby' => [
                        'title' => '爱好',
                        'type' => 'checkbox',
                        'verify' => 'require|arrayIn:write,read',
                        'options' => Hobby::options()
                    ],
                    'category_ids' => [
                        'title' => '喜欢的分类',
                        'type' => 'tree',
                        'verify' => 'require|arrayIn:' . implode(',', Category::instance()->ids()),
                        'nodes' => Category::instance()->nodes()
                    ],
                    'friend_ids' => [
                        'title' => '好友',
                        'type' => 'dropdown_search',
                        'verify' => 'array',
                        'url' => url('friendOptions'),
                    ],
                    'area' => [
                        'title' => '地址',
                        'type' => 'area',
                        'verify' => 'require|area:district',
                    ],
                    'intro' => [
                        'title' => '简介',
                        'type' => 'textarea',
                        'verify' => 'require',
                        'desc' => '这是简介',
                    ],
                    'document' => [
                        'title' => '个人文档',
                        'type' => 'file',
                    ],
                    'other_document' => [
                        'title' => '其他文档',
                        'type' => 'files',
                        'max' => 3,
                    ],
                ];
                break;
            case 'other':
                $field = [
                    'demo_show_time' => [
                        'title' => '操作时间',
                        'type' => 'show_time',
                        //'value'=>'2020-12-03 19:17:12',
                    ],
                    'hidden_test' => [
                        'type' => 'hidden',
                        'value' => 123
                    ],
                    'password_test' => [
                        'title' => '密码测试',
                        'type' => 'password',
                    ],
                    'year_test' => [
                        'title' => '年测试',
                        'type' => 'year',
                        'range' => true,
                    ],
                    'month_test' => [
                        'title' => '月测试',
                        'type' => 'month',
                        'range' => true,
                    ],
                    'date_test' => [
                        'title' => '日期测试',
                        'type' => 'date',
                        'value' => '2020-11-15 - 2020-11-17',
                    ],
                    'datetime_test' => [
                        'title' => '日期时间测试',
                        'type' => 'datetime',
                    ],
                    'time_test' => [
                        'title' => '时间测试',
                        'type' => 'time',
                    ],
                    'switch_test' => [
                        'title' => '开关测试',
                        'type' => 'switch',
                    ],
                    'editor_test' => [
                        'title' => '富文本测试',
                        'type' => 'editor',
                    ],
                    'editor2_test' => [
                        'title' => '富文本测试2',
                        'type' => 'editor',
                    ],
                    'dropdown_search_test' => [
                        'title' => '下拉搜索',
                        'type' => 'dropdown_search',
                        'value' => [100, 101, 102],
                        'verify' => 'array',
                        'url' => url('demo/formDemo/dropdownSearchOptions')
                    ],
                ];
                break;
        }
        return $field;
    }

    public function submitByAddGeneralExample($data, $tab_data) {
        $insertData = [
            'avatar' => $data['avatar'],
            'name_cn' => $data['name_cn'],
            'name_en' => $data['name_en'],
            'sex' => $data['sex'],
            'color' => $data['color'],
            'age' => $data['age'],
            'grade' => $data['grade'],
            'album' => implode(',', $data['album']),
            'hobby' => implode(',', $data['hobby']),
            'category_ids' => $data['category_ids'] ? json_encode($data['category_ids']) : '',
            'friend_ids' => $data['friend_ids'] ? json_encode($data['friend_ids']) : '',
            'province' => $data['area'] && isset($data['area']['province']) ? $data['area']['province'] : '',
            'city' => $data['area'] && isset($data['area']['city']) ? $data['area']['city'] : '',
            'district' => $data['area'] && isset($data['area']['district']) ? $data['area']['district'] : '',
            'document' => $data['intro'] ? json_encode($data['intro']) : '',
            'other_document' => $data['other_document'] ? json_encode($data['other_document']) : '',
            'intro' => $data['intro'],
        ];
        $this->model->addRow($insertData);
        return success_json(['reload' => true]);
    }

    // edit general example

    public function fieldByEditGeneralExample($tab) {
        $id = input('get.id/d');
        $field = [];
        switch ($tab) {
            case 'base':
                $field = [
                    'id' => [
                        'type' => 'hidden',
                        'value' => $id
                    ],
                    'avatar' => [
                        'title' => '头像',
                        'type' => 'img',
                    ],
                    'name_cn' => ['title' => '中文姓名', 'verify' => 'require|chs|checkNameCn', 'desc' => '只能输入汉字'],
                    'name_en' => ['title' => '英文姓名', 'verify' => 'require|chsDash', 'desc' => '只能输入汉字、字母、数字和下划线_及破折号-'],
                    'sex' => [
                        'title' => '性别',
                        'type' => 'radio',
                        'verify' => 'require|in:man,woman',
                        'options' => Sex::options()
                    ],
                    'album' => [
                        'title' => '相册',
                        'type' => 'imgs',
                        'max' => 3,
                    ],
                    'color' => [
                        'title' => '喜欢的颜色',
                        'type' => 'color',
                    ],
                    "markdown_test1" => [
                        'title' => 'Markdown',
                        'type' => 'markdown',
                        'desc' => 'markdown提示语',
                    ],
                ];
                break;
            case 'other':
                $field = [
                    'age' => ['title' => '年龄', 'verify' => 'require|positiveInteger'],
                    'grade' => [
                        'title' => '年级',
                        'type' => 'select',
                        'search' => true,
                        'verify' => 'require|in:1,2,3,4',
                        'options' => Grade::options()
                    ],
                    'hobby' => [
                        'title' => '爱好',
                        'type' => 'checkbox',
                        'verify' => 'require|arrayIn:write,read',
                        'options' => Hobby::options()
                    ],
                    'category_ids' => [
                        'title' => '喜欢的分类',
                        'type' => 'tree',
                        'verify' => 'require|arrayIn:' . implode(',', Category::instance()->ids()),
                        'nodes' => Category::instance()->nodes()
                    ],
                    'friend_ids' => [
                        'title' => '好友',
                        'type' => 'dropdown_search',
                        'verify' => 'array',
                        'url' => url('friendOptions'),
                    ],
                    'area' => [
                        'title' => '地址',
                        'type' => 'area',
                        'verify' => 'require|area:district',
                    ],
                    'intro' => [
                        'title' => '简介',
                        'type' => 'textarea',
                        'verify' => 'require',
                        'desc' => '这是简介',
                    ],
                    'document' => [
                        'title' => '个人文档',
                        'type' => 'file',
                    ],
                    'other_document' => [
                        'title' => '其他文档',
                        'type' => 'files',
                        'max' => 3,
                    ],
                    "markdown_test2" => [
                        'title' => 'Markdown',
                        'type' => 'markdown',
                        'desc' => 'markdown提示语',
                    ],
                ];
                break;
        }
        return $field;
    }

    public function loadByEditGeneralExample() {
        $id = input('get.id/d');
        $rowData = $this->model->getOwnRow([["id", "eq", $id]]);
        $rowData['album'] = explode(',', $rowData['album']);
        $rowData['hobby'] = explode(',', $rowData['hobby']);
        $rowData['area'] = ['province' => $rowData['province'], 'city' => $rowData['city'], 'district' => $rowData['district']];
        $rowData['document'] = $rowData['document'] ? json_decode($rowData['document']) : '';
        $rowData['other_document'] = $rowData['other_document'] ? json_decode($rowData['other_document']) : '';
        return $rowData;
    }

    public function submitByEditGeneralExample($data, $tab_data) {
        $data = [
            'id' => $data['id'],
            'avatar' => $data['avatar'],
            'name_cn' => $data['name_cn'],
            'name_en' => $data['name_en'],
            'sex' => $data['sex'],
            'color' => $data['color'],
            'age' => $data['age'],
            'grade' => $data['grade'],
            'album' => implode(',', $data['album']),
            'hobby' => implode(',', $data['hobby']),
            'category_ids' => $data['category_ids'] ? json_encode($data['category_ids']) : '',
            'friend_ids' => $data['friend_ids'] ? json_encode($data['friend_ids']) : '',
            'province' => $data['area'] && isset($data['area']['province']) ? $data['area']['province'] : '',
            'city' => $data['area'] && isset($data['area']['city']) ? $data['area']['city'] : '',
            'district' => $data['area'] && isset($data['area']['district']) ? $data['area']['district'] : '',
            'intro' => $data['intro'],
            'document' => $data['document'] ? json_encode($data['document']) : '',
            'other_document' => $data['other_document'] ? json_encode($data['other_document']) : '',
        ];
        $this->model->change($data);
        return success_json(['reload' => true]);
    }

    // friend options

    public function friendOptions() {
        $data = input('get.');
        // 输入关键字
        $keywords = filter_sql($data['keywords']);
        // 使用 , 分割的初始值
        $ids = filter_sql($data['ids']);
        // 进行数据查询
        $whereArr = [];
        if ($keywords) $whereArr[] = ['name_cn|name_en', 'like', $keywords . '%'];
        if ($ids) $whereArr[] = ['id', 'in', $ids];
        $fieldArr = ['id', 'name_cn', 'name_en'];
        $datas = $this->model->getOwnRows($whereArr, $fieldArr, ['id' => 'desc'], 0, 20);
        $items = [];
        foreach ($datas as $data) {
            $items[$data['id']] = "{$data['name_cn']}（{$data['name_en']}）";
        }
        // 返回数据
        return success_json($items);
    }

}